using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Opc.Ua;
using OpcUaHelper;

namespace twistmachinev2
{
    public partial class FrmOPCUAServerBrowser : XtraForm
    {
        private twistmachinev2.OpcUaClient opcUaClient;
        private bool isConnected = false;
        private System.Windows.Forms.Timer refreshTimer;

        public FrmOPCUAServerBrowser()
        {
            InitializeComponent();
            InitializeOpcClient();
            InitializeTimer();
        }

        private void InitializeOpcClient()
        {
            opcUaClient = new twistmachinev2.OpcUaClient();
        }

        private void InitializeTimer()
        {
            refreshTimer = new System.Windows.Forms.Timer();
            refreshTimer.Interval = 5000; // 1秒刷新一次
            refreshTimer.Tick += RefreshTimer_Tick;
        }

        private void RefreshTimer_Tick(object sender, EventArgs e)
        {
            if (isConnected)
            {
                RefreshSelectedNodeValue();
            }
        }

        private async void btnConnect_Click(object sender, EventArgs e)
        {
            try
            {
                if (!isConnected)
                {
                    var connectResult = await opcUaClient.ConnectAsync(txtAddress.Text);
                    if (connectResult.IsSuccess)
                    {
                        isConnected = true;
                        btnConnect.Text = "Disconnect";
                        lblStatus.Text = "已连接";
                        lblStatus.BackColor = Color.Green;
                        lblConnectedInfo.Text = $"Connected [{txtAddress.Text}]";
                        
                        // 开始浏览服务器节点
                        await BrowseServerNodes();
                        refreshTimer.Start();
                    }
                    else
                    {
                        MessageBox.Show($"连接失败: {connectResult.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        lblStatus.Text = "连接失败";
                        lblStatus.BackColor = Color.Red;
                    }
                }
                else
                {
                    // 断开连接
                    refreshTimer.Stop();
                    opcUaClient.Disconnect();
                    isConnected = false;
                    btnConnect.Text = "Connect";
                    lblStatus.Text = "已断开";
                    lblStatus.BackColor = Color.Gray;
                    lblConnectedInfo.Text = "";
                    treeViewServer.Nodes.Clear();
                    dataGridViewNodes.Rows.Clear();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"连接操作失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private async Task BrowseServerNodes()
        {
            try
            {
                treeViewServer.Nodes.Clear();
                
                // 从根节点开始浏览，只加载第一层
                await BrowseNodeRecursive(null, "i=85", "Objects", 1); // 只加载1层
                
                // 添加其他根节点
                await BrowseNodeRecursive(null, "i=86", "Types", 0); // 不预加载子节点
                await BrowseNodeRecursive(null, "i=87", "Views", 0); // 不预加载子节点
                
                // 只展开第一层
                foreach (TreeNode node in treeViewServer.Nodes)
                {
                    if (node.Nodes.Count > 0)
                    {
                        node.Expand();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"浏览服务器节点失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        private async Task BrowseNodeRecursive(TreeNode parentNode, string nodeId, string nodeName, int maxDepth)
        {
            TreeNode currentNode;
            if (parentNode == null)
            {
                currentNode = treeViewServer.Nodes.Add(nodeName, nodeName);
            }
            else
            {
                currentNode = parentNode.Nodes.Add(nodeName, nodeName);
            }
            currentNode.Tag = nodeId;
            
            // 检查是否有子节点，如果有则添加一个占位符节点
            var hasChildren = await CheckHasChildren(nodeId);
            if (hasChildren)
            {
                // 添加占位符节点，用于显示展开图标
                currentNode.Nodes.Add("loading...", "正在加载...");
            }
            
            // 只在初始加载时递归一层
            if (maxDepth > 0)
            {
                try
                {
                    var browseResult = await opcUaClient.BrowseAsync(nodeId);
                    if (browseResult.IsSuccess && browseResult.Content != null)
                    {
                        // 移除占位符
                        currentNode.Nodes.Clear();
                        
                        foreach (var reference in browseResult.Content)
                        {
                            if (reference.NodeClass == NodeClass.Object || reference.NodeClass == NodeClass.Variable)
                            {
                                string childNodeId = reference.NodeId.ToString();
                                string childNodeName = reference.DisplayName.Text;
                                
                                // 只递归一层
                                await BrowseNodeRecursive(currentNode, childNodeId, childNodeName, maxDepth - 1);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    // 记录错误但继续处理其他节点
                    System.Diagnostics.Debug.WriteLine($"浏览节点 {nodeId} 失败: {ex.Message}");
                }
            }
        }

        private async Task<bool> CheckHasChildren(string nodeId)
        {
            try
            {
                // 使用动态浏览检查是否有子节点
                var browseResult = await opcUaClient.BrowseAsync(nodeId);
                if (browseResult.IsSuccess && browseResult.Content != null)
                {
                    // 检查是否有Object或Variable类型的子节点
                    return browseResult.Content.Any(r => r.NodeClass == NodeClass.Object || r.NodeClass == NodeClass.Variable);
                }
                return false;
            }
            catch
            {
                return false;
            }
        }
        
        private async Task LoadNodeDetails(TreeNode parentNode, string nodeId)
        {
            try
            {
                // 读取节点的基本属性
                var readResult = await opcUaClient.ReadAsync<object>(nodeId);
                if (readResult.IsSuccess)
                {
                    var nodeValue = readResult.Content;
                    
                    // 添加节点属性作为子节点
                    TreeNode valueNode = parentNode.Nodes.Add($"值: {nodeValue?.ToString() ?? "null"}");
                    valueNode.Tag = $"{nodeId}#Value";
                    
                    TreeNode typeNode = parentNode.Nodes.Add($"数据类型: {nodeValue?.GetType().Name ?? "未知"}");
                    typeNode.Tag = $"{nodeId}#DataType";
                    
                    TreeNode accessNode = parentNode.Nodes.Add($"访问级别: CurrentRead,Write");
                    accessNode.Tag = $"{nodeId}#AccessLevel";
                    
                    TreeNode nodeIdNode = parentNode.Nodes.Add($"节点ID: {nodeId}");
                    nodeIdNode.Tag = $"{nodeId}#NodeId";
                }
                else
                {
                    // 如果读取失败，显示错误信息
                    TreeNode errorNode = parentNode.Nodes.Add($"读取失败: {readResult.Message}");
                    errorNode.Tag = $"{nodeId}#Error";
                }
            }
            catch (Exception ex)
            {
                // 添加错误信息节点
                TreeNode errorNode = parentNode.Nodes.Add($"错误: {ex.Message}");
                errorNode.Tag = $"{nodeId}#Exception";
            }
        }
        
        private async Task ShowNodeDetailsInGrid(string nodeId)
        {
            try
            {
                dataGridViewNodes.Rows.Clear();
                
                // 读取节点的基本属性
                var readResult = await opcUaClient.ReadAsync<object>(nodeId);
                if (readResult.IsSuccess)
                {
                    var nodeValue = readResult.Content;
                    string dataType = nodeValue?.GetType().Name ?? "Object";
                    string accessLevel = "CurrentRead,Write";
                    string description = "节点值";
                    
                    // 在DataGridView中显示完整信息：名称、值、类型、访问级别、描述
                    dataGridViewNodes.Rows.Add("节点值", nodeValue?.ToString() ?? "null", dataType, accessLevel, description);
                }
                else
                {
                    // 如果读取失败，显示错误信息
                    dataGridViewNodes.Rows.Add("读取状态", "失败", "Error", "None", readResult.Message ?? "读取失败");
                }
            }
            catch (Exception ex)
            {
                // 显示错误信息
                dataGridViewNodes.Rows.Clear();
                dataGridViewNodes.Rows.Add("错误", ex.Message, "Exception", "None", "发生异常");
            }
        }
        
        private async Task LoadChildNodes(TreeNode parentNode, string nodeId)
        {
            try
            {
                var browseResult = await opcUaClient.BrowseAsync(nodeId);
                if (browseResult.IsSuccess && browseResult.Content != null)
                {
                    foreach (var reference in browseResult.Content)
                    {
                        if (reference.NodeClass == NodeClass.Object || reference.NodeClass == NodeClass.Variable)
                        {
                            string childNodeId = reference.NodeId.ToString();
                            string childNodeName = reference.DisplayName.Text;
                            
                            // 创建子节点
                            TreeNode childNode = parentNode.Nodes.Add(childNodeName, childNodeName);
                            childNode.Tag = childNodeId;
                            
                            // 检查子节点是否还有子节点
                            var hasGrandChildren = await CheckHasChildren(childNodeId);
                            if (hasGrandChildren)
                            {
                                // 添加占位符节点
                                childNode.Nodes.Add("loading...", "正在加载...");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载子节点失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private async void treeViewServer_BeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            try
            {
                // 检查是否需要动态加载子节点
                if (e.Node.Nodes.Count == 1)
                {
                    string placeholderText = e.Node.Nodes[0].Text;
                    
                    if (placeholderText == "正在加载...")
                    {
                        // 移除占位符节点
                        e.Node.Nodes.Clear();
                        
                        // 获取节点ID
                        string nodeId = e.Node.Tag?.ToString();
                        if (!string.IsNullOrEmpty(nodeId))
                        {
                            // 动态加载子节点
                            await LoadChildNodes(e.Node, nodeId);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"展开节点失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                e.Cancel = true;
            }
        }

        private async void treeViewServer_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node?.Tag != null)
            {
                string nodeId = e.Node.Tag.ToString();
                txtSelectedNodeId.Text = nodeId;
                
                // 检查是否是叶子节点（没有子节点）
                bool isLeafNode = e.Node.Nodes.Count == 0;
                
                if (isLeafNode)
                {
                    // 如果是叶子节点，显示该节点的详细信息
                    await ShowNodeDetailsInGrid(nodeId);
                }
                else
                {
                    // 如果不是叶子节点，浏览选中节点的子节点并显示在DataGridView中
                    await BrowseSelectedNode(nodeId);
                }
            }
        }

        private async Task BrowseSelectedNode(string nodeId)
        {
            try
            {
                dataGridViewNodes.Rows.Clear();
                
                // 使用动态浏览获取子节点
                var browseResult = await opcUaClient.BrowseAsync(nodeId);
                if (browseResult.IsSuccess && browseResult.Content != null)
                {
                    foreach (var reference in browseResult.Content)
                    {
                        string childNodeId = reference.NodeId.ToString();
                        string childNodeName = reference.DisplayName.Text;
                        string nodeClass = reference.NodeClass.ToString();
                        
                        // 尝试读取节点值（仅对Variable类型）
                        string nodeValue = "";
                        string description = "";
                        
                        string accessLevel = "";
                        string dataType = "";
                        
                        if (reference.NodeClass == NodeClass.Variable)
                         {
                             try
                             {
                                 var readResult = await opcUaClient.ReadAsync<object>(childNodeId);
                                 if (readResult.IsSuccess)
                                 {
                                     nodeValue = readResult.Content?.ToString() ?? "null";
                                     dataType = readResult.Content?.GetType().Name ?? "Object";
                                 }
                                 else
                                 {
                                     nodeValue = "Failed to read";
                                     description = readResult.Message;
                                     dataType = "Unknown";
                                 }
                                 
                                 // 设置访问级别
                                 accessLevel = "CurrentRead,Write";
                             }
                             catch
                             {
                                 nodeValue = "Read error";
                                 dataType = "Error";
                                 accessLevel = "None";
                             }
                         }
                         else
                         {
                             nodeValue = "-";
                             description = $"{nodeClass} node";
                             dataType = nodeClass;
                             accessLevel = nodeClass == "Object" ? "Browse" : "None";
                         }
                         
                         // 添加到DataGridView - 显示完整信息：名称、值、类型、访问级别、描述
                         dataGridViewNodes.Rows.Add(childNodeName, nodeValue, dataType, accessLevel, description);
                    }
                }
                else
                {
                    // 如果浏览失败，回退到静态节点定义
                    switch (nodeId)
                    {
                        case "i=85": // Objects
                            await AddNodeToGrid("Server", "i=2253");
                            break;
                            
                        case "i=2253": // Server
                            await AddNodeToGrid("ServerArray", "i=2254");
                            await AddNodeToGrid("NamespaceArray", "i=2255");
                            await AddNodeToGrid("ServerStatus", "i=2256");
                            await AddNodeToGrid("ServerCapabilities", "i=2268");
                            await AddNodeToGrid("ServerDiagnostics", "i=2274");
                            await AddNodeToGrid("VendorServerInfo", "i=2294");
                            await AddNodeToGrid("ServerRedundancy", "i=2296");
                            break;
                            
                        case "i=2256": // ServerStatus
                            await AddNodeToGrid("StartTime", "i=2257");
                            await AddNodeToGrid("CurrentTime", "i=2258");
                            await AddNodeToGrid("State", "i=2259");
                            await AddNodeToGrid("BuildInfo", "i=2260");
                            break;
                            
                        case "i=2260": // BuildInfo
                            await AddNodeToGrid("ProductUri", "i=2261");
                            await AddNodeToGrid("ManufacturerName", "i=2262");
                            await AddNodeToGrid("ProductName", "i=2263");
                            await AddNodeToGrid("SoftwareVersion", "i=2264");
                            await AddNodeToGrid("BuildNumber", "i=2265");
                            await AddNodeToGrid("BuildDate", "i=2266");
                            break;
                            
                        case "i=2268": // ServerCapabilities
                            await AddNodeToGrid("ServerProfileArray", "i=2269");
                            await AddNodeToGrid("LocaleIdArray", "i=2271");
                            await AddNodeToGrid("MinSupportedSampleRate", "i=2272");
                            await AddNodeToGrid("MaxBrowseContinuationPoints", "i=2735");
                            break;
                            
                        case "i=2274": // ServerDiagnostics
                            await AddNodeToGrid("ServerDiagnosticsSummary", "i=2275");
                            break;
                            
                        case "i=86": // Types
                            await AddNodeToGrid("ObjectTypes", "i=88");
                            await AddNodeToGrid("VariableTypes", "i=87");
                            await AddNodeToGrid("DataTypes", "i=89");
                            await AddNodeToGrid("ReferenceTypes", "i=90");
                            break;
                            
                        case "i=88": // ObjectTypes
                            await AddNodeToGrid("BaseObjectType", "i=58");
                            await AddNodeToGrid("FolderType", "i=61");
                            break;
                            
                        case "i=87": // VariableTypes
                            await AddNodeToGrid("BaseVariableType", "i=62");
                            await AddNodeToGrid("BaseDataVariableType", "i=63");
                            await AddNodeToGrid("PropertyType", "i=68");
                            break;
                            
                        case "i=89": // DataTypes
                            await AddNodeToGrid("BaseDataType", "i=24");
                            await AddNodeToGrid("Boolean", "i=1");
                            await AddNodeToGrid("Number", "i=26");
                            await AddNodeToGrid("String", "i=12");
                            break;
                            
                        case "i=26": // Number
                            await AddNodeToGrid("Integer", "i=27");
                            break;
                            
                        case "i=90": // ReferenceTypes
                            await AddNodeToGrid("References", "i=31");
                            break;
                            
                        case "i=31": // References
                            await AddNodeToGrid("HierarchicalReferences", "i=33");
                            break;
                            
                        case "i=33": // HierarchicalReferences
                            await AddNodeToGrid("HasChild", "i=34");
                            break;
                            
                        case "i=34": // HasChild
                            await AddNodeToGrid("Organizes", "i=35");
                            await AddNodeToGrid("HasComponent", "i=47");
                            await AddNodeToGrid("HasProperty", "i=46");
                            break;
                            
                        default:
                            // 对于其他节点，直接读取其值
                            await AddNodeToGrid("Value", nodeId);
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"浏览选中节点失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        private async Task AddNodeToGrid(string name, string nodeId)
        {
            try
            {
                string value = "";
                string dataType = "";
                string accessLevel = "";
                string description = "";
                
                // 读取节点值
                var readResult = await opcUaClient.ReadAsync<object>(nodeId);
                if (readResult.IsSuccess)
                {
                    value = readResult.Content?.ToString() ?? "";
                    dataType = readResult.Content?.GetType().Name ?? "Object";
                    accessLevel = "CurrentRead,Write";
                    description = $"节点: {name}";
                }
                else
                {
                    value = "读取失败";
                    dataType = "Unknown";
                    accessLevel = "None";
                    description = readResult.Message ?? "读取失败";
                }
                
                // 显示完整信息：名称、值、类型、访问级别、描述
                dataGridViewNodes.Rows.Add(name, value, dataType, accessLevel, description);
            }
            catch (Exception ex)
            {
                dataGridViewNodes.Rows.Add(name, $"错误: {ex.Message}", "Exception", "None", "发生异常");
            }
        }

        private async void RefreshSelectedNodeValue()
        {
            if (dataGridViewNodes.SelectedRows.Count > 0)
            {
                var selectedRow = dataGridViewNodes.SelectedRows[0];
                string nodeName = selectedRow.Cells["colName"].Value?.ToString();
                
                if (!string.IsNullOrEmpty(nodeName))
                {
                    try
                    {
                        // 根据当前选中的TreeView节点类型来决定刷新方式
                        if (!string.IsNullOrEmpty(txtSelectedNodeId.Text))
                        {
                            // 获取当前选中的TreeView节点
                            var selectedTreeNode = treeViewServer.SelectedNode;
                            if (selectedTreeNode != null)
                            {
                                // 检查是否是叶子节点（最后一级节点）
                                bool isLeafNode = selectedTreeNode.Nodes.Count == 0;
                                
                                if (isLeafNode)
                                {
                                    // 如果是叶子节点，显示该节点的详细信息
                                    await ShowNodeDetailsInGrid(txtSelectedNodeId.Text);
                                }
                                else
                                {
                                    // 如果不是叶子节点，浏览选中节点的子节点
                                    await BrowseSelectedNode(txtSelectedNodeId.Text);
                                }
                            }
                            else
                            {
                                // 如果没有选中TreeView节点，默认浏览子节点
                                await BrowseSelectedNode(txtSelectedNodeId.Text);
                            }
                        }
                    }
                    catch
                    {
                        // 忽略刷新错误
                    }
                }
            }
        }

        private async void btnRefresh_Click(object sender, EventArgs e)
        {
            if (isConnected)
            {
                if (!string.IsNullOrEmpty(txtSelectedNodeId.Text))
                {
                    // 获取当前选中的TreeView节点
                    var selectedNode = treeViewServer.SelectedNode;
                    if (selectedNode != null)
                    {
                        // 检查是否是叶子节点
                        bool isLeafNode = selectedNode.Nodes.Count == 0;
                        
                        if (isLeafNode)
                        {
                            // 如果是叶子节点，显示该节点的详细信息
                            await ShowNodeDetailsInGrid(txtSelectedNodeId.Text);
                        }
                        else
                        {
                            // 如果不是叶子节点，浏览选中节点的子节点
                            await BrowseSelectedNode(txtSelectedNodeId.Text);
                        }
                    }
                    else
                    {
                        // 如果没有选中节点，默认浏览子节点
                        await BrowseSelectedNode(txtSelectedNodeId.Text);
                    }
                }
                else
                {
                    await BrowseServerNodes();
                }
            }
        }

        private void dataGridViewNodes_SelectionChanged(object sender, EventArgs e)
        {
            // 当选择变化时，可以在这里处理
        }

        private void FrmOPCUAServerBrowser_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                refreshTimer?.Stop();
                refreshTimer?.Dispose();
                
                if (isConnected)
                {
                    opcUaClient?.Disconnect();
                }
                
                opcUaClient?.Dispose();
            }
            catch
            {
                // 忽略关闭时的错误
            }
        }
    }
}
